package com.tron.thread.semaphore;

import java.util.concurrent.Semaphore;

public class BoundSource {
    private Semaphore semaphore;
    private Integer permits;

    public BoundSource(Integer permits) {
        this.semaphore = new Semaphore(permits);
        this.permits = permits;
    }

    public void use() throws InterruptedException {
        semaphore.acquire();
        System.out.println(Thread.currentThread().getId()+"->获取资源");
        try {
            doUse();
        } finally {
            semaphore.release();
            System.out.println(Thread.currentThread().getId()+"释放资源");
        }
    }

    private void doUse() throws InterruptedException {
        System.out.println("使用资源");
        /**
         * 资源总数 - 可用资源 = 已使用资源
         */
        System.out.println("已使用资源："+ (permits - semaphore.availablePermits()));
        Thread.sleep(1000);
    }
}
